package com.peng.mybatis.binding;

import cn.hutool.core.util.StrUtil;
import com.peng.mybatis.mapping.MappedStatement;
import com.peng.mybatis.mapping.SqlCommandType;
import com.peng.mybatis.session.Configuration;
import com.peng.mybatis.session.SqlSession;
import lombok.Getter;

import java.lang.reflect.Method;

/**
 * mapper文件中一个方法的执行过程
 */
public class MapperMethod {

    private final SqlCommand command;

    public MapperMethod(Configuration configuration, Class<?> mapperInterface, Method method) {
        this.command = new SqlCommand(configuration, mapperInterface, method);
    }

    public Object execute(SqlSession sqlSession, Object[] parameter) {
        switch (command.getType()) {
            case INSERT, UPDATE, DELETE -> {
                return null;
            }
            case SELECT -> {
                return sqlSession.selectOne(command.getName(), parameter);
            }
            default -> throw new IllegalArgumentException("不支持的SQL类型：" + command.getType());
        }
    }

    @Getter
    public static class SqlCommand {

        private final String name;

        private final SqlCommandType type;

        SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
            String statementName = StrUtil.join(".", mapperInterface.getName(), method.getName());
            MappedStatement mappedStatement = configuration.getMappedStatement(statementName);
            name = mappedStatement.getId();
            type = mappedStatement.getSqlCommandType();
        }

    }

}
